# @Version        : 1.0
# @Update Time    : 2025/3/13 15:51
# @File           : cart_view.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息

# views/cart_view.py
import flet as ft
from services.cart_service import CartService


# 创建选中商品类
class CartItem:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity

    # 计算价格
    def calculate_price(self):
        return self.price * self.quantity


class CartView(ft.Column):
    def __init__(self, page: ft.Page, params: dict = None):
        super().__init__()
        self.page = page
        self.params = params
        self.expand = True
        self.total = ft.Ref[ft.Text]()  # 初始总价
        self.cart_service = CartService()  # 初始化CartService
        # 存储商品的数量
        self.cart_items: dict[str, CartItem] = {}
        self.selected_items: set = set()  # 用于存储选中的商品及其数量
        self.quantity_refs: dict[str, ft.Ref[ft.Text]] = {}  # 用于存储每个商品的数量引用
        self.title = ft.Ref[ft.Text]()
        self.build_ui()

    def build_ui(self):
        # 顶部标签
        title_label = ft.Text(
            "我的购物车", color=ft.colors.GREEN_800, size=24, weight=ft.FontWeight.BOLD,
            style=ft.TextThemeStyle.HEADLINE_MEDIUM
        )

        # 商品列表
        cart_items = ft.ListView(
            expand=True,
            spacing=5,  # 减少间距以显示更多商品
            height=400  # 增加高度以显示更多商品
        )
        # 使用CartService获取商品数据
        cart_items.controls.extend(
            [
                self._build_cart_item(item["name"], item["image_path"], item["spec"], item["price"], item["quantity"])
                for item in self.cart_service.get_cart_items()
            ]
        )

        # 优惠券栏
        coupon_row = ft.ListTile(
            leading=ft.Icon(ft.icons.DISCOUNT, color=ft.colors.GREEN_800),
            title=ft.Text("津贴优惠券"),
            trailing=ft.FilledButton(
                "使用",
                style=ft.ButtonStyle(
                    bgcolor=ft.colors.GREEN_800,
                    shape=ft.RoundedRectangleBorder(radius=8)
                )
            ),
            on_click=lambda _: print("打开优惠券选择")
        )

        # 总计栏
        self.total_bar = ft.Container(
            content=ft.Row(
                [
                    ft.Text("总计：", size=18),
                    ft.Text(
                        "¥ 0.00",
                        ref=self.total,
                        size=24,
                        color=ft.colors.GREEN_800,
                        weight=ft.FontWeight.BOLD
                    )
                ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN
            ),
            padding=10,
            bgcolor=ft.colors.GREY_100,
            border_radius=12
        )

        # 底部操作栏
        bottom_bar = ft.FilledButton(
            "前往结算",
            icon=ft.icons.SHOPPING_BAG,
            style=ft.ButtonStyle(
                bgcolor=ft.colors.GREEN,
                padding=ft.padding.symmetric(horizontal=30, vertical=15)
            ),
            expand=1,
            on_click=lambda _: print("前往结算"),
        )

        self.controls = [
            title_label,  # 替换AppBar为标签
            ft.Container(
                content=ft.Column(
                    [
                        cart_items,
                        coupon_row,
                        self.total_bar
                    ], spacing=5
                ),
                padding=10,
                expand=True
            ),
            ft.Container(bottom_bar, padding=5, alignment=ft.alignment.center)
        ]

    def _build_cart_item(self, name, image_path, spec, price, quantity):
        checkbox = ft.Checkbox(
            label="", value=False, on_change=lambda e: self._on_checkbox_change(e, name, price, quantity)
        )
        self.cart_items[name] = CartItem(name, price, quantity)
        return ft.Dismissible(
            content=ft.Container(
                content=ft.Row(
                    [
                        checkbox,
                        # 商品图片和规格
                        ft.Row(
                            [
                                ft.Image(
                                    src=image_path,
                                    width=40,  # 缩小图片宽度
                                    height=40,  # 缩小图片高度
                                    fit=ft.ImageFit.CONTAIN
                                ),
                                ft.Text(spec, color=ft.colors.GREY_600, size=12)  # 缩小字体大小
                            ], spacing=5, alignment=ft.MainAxisAlignment.START  # 减少间距
                        ),
                        # 价格
                        ft.Text(
                            f"{spec}/{price}￥",
                            color=ft.colors.GREEN_800,
                            weight=ft.FontWeight.BOLD,
                            size=12  # 缩小字体大小
                        ),
                        # 数量调整
                        ft.Row(
                            [
                                ft.IconButton(
                                    ft.icons.REMOVE,
                                    on_click=lambda e: self._update_quantity(-1, name),
                                    icon_color=ft.colors.GREEN_800,
                                    bgcolor=ft.colors.TRANSPARENT,
                                    icon_size=16  # 缩小图标大小
                                ),
                                ft.Text(
                                    str(quantity), ref=self.quantity_refs.setdefault(name, ft.Ref[ft.Text]()), width=20,
                                    # 缩小文本框宽度
                                    text_align=ft.TextAlign.CENTER
                                ),
                                ft.IconButton(
                                    ft.icons.ADD,
                                    on_click=lambda e: self._update_quantity(1, name),
                                    icon_color=ft.colors.GREEN_800,
                                    bgcolor=ft.colors.TRANSPARENT,
                                    icon_size=16  # 缩小图标大小
                                )
                            ], spacing=3  # 减少间距
                        )
                    ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN
                ),
                bgcolor=ft.colors.GREEN_100,
                padding=5,  # 减少内边距
                border_radius=8
            ),
            background=ft.Container(bgcolor=ft.colors.GREEN),
            secondary_background=ft.Container(bgcolor=ft.colors.RED),
            dismiss_direction=ft.DismissDirection.HORIZONTAL,
            on_dismiss=lambda e: self._on_dismiss(e, name),
            # on_update=handle_update,
            on_confirm_dismiss=lambda e: self.handle_confirm_dismiss(e),
            dismiss_thresholds={
                ft.DismissDirection.END_TO_START: 0.9,
                ft.DismissDirection.START_TO_END: 0.9,
            },
        )

    def handle_confirm_dismiss(self, e: ft.DismissibleDismissEvent):
        # 直接删除商品，不再弹出确认对话框
        e.control.confirm_dismiss(True)

    def _remove_item_from_cart(self, name):
        self.cart_items.pop(name, None)
        self.selected_items.discard(name)
        self._calculate_total()

    def _on_dismiss(self, e, name):
        # 打印被移出的商品
        print(f"移除商品: {name}")
        e.control.parent.controls.remove(e.control)
        self.page.update()
        self._remove_item_from_cart(name)

    def _on_checkbox_change(self, e, name, price, quantity):
        if e.control.value:
            self.selected_items.add(name)
        else:
            self.selected_items.discard(name)
        self._calculate_total()

    def _calculate_total(self):
        # 从CartService中获取商品价格信息
        # 计算总价时，使用商品名称从cart_items中获取价格
        total = sum(self.cart_items.get(name, 0).calculate_price() for name in self.selected_items)
        self.total.current.value = f"¥{total:.2f}"
        self.total.current.update()

    def _update_quantity(self, delta, name):
        # 数量更新逻辑
        if name in self.quantity_refs:
            quantity = self.quantity_refs[name].current.value
            if quantity is not None:
                new_quantity = max(0, int(quantity) + delta)
                self.cart_items[name].quantity = new_quantity
                print(f"{name}数量更新为{new_quantity}")
                self.quantity_refs[name].current.value = str(new_quantity)
                self.quantity_refs[name].current.update()
                # 判断是否需要更新选中商品列表
                if name in self.selected_items:
                    self._calculate_total()
